﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Zeenck.Models;

namespace Zeenck.Controllers
{
    public class LoginController : Controller
    {
        [HttpGet]
        public ActionResult Begin(String returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return Redirect(Url.Root(false));
            }

            var model = new LoginAndRegistration();

            if (!String.IsNullOrWhiteSpace(returnUrl))
            {
                model.Login.ReturnUrl = returnUrl;
            }

            return View("LoginAndRegistration/LoginAndRegistration", model);
        }

        [HttpPost]
        public ActionResult Submit(Login model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (Membership.ValidateUser(model.UserName, model.Password))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    
                    return Redirect(Url.Root(false));
                }
                
                ModelState.AddModelError("Username", "The user name or password provided is incorrect.");
            }

            var parentModel = new LoginAndRegistration { Login = model };
            return View("LoginAndRegistration/LoginAndRegistration", parentModel);
        }

        [HttpGet]
        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
    }
}
